package com.avic.rong.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avic.rong.BaseFragment;
import com.avic.rong.MainActivity;
import com.avic.rong.R;
import com.avic.rong.activity.TestWebActivity;
import com.avic.rong.activity.login.LoginPhoneActivity;
import com.avic.rong.activity.product.RankingListActivity;
import com.avic.rong.adapter.show.FollowListAdapter;
import com.avic.rong.adapter.show.SjbzAdapter;
import com.avic.rong.api.RecommendApi;
import com.avic.rong.bean.show_bean.EsInfoBean;
import com.avic.rong.bean.show_bean.ShowBean;
import com.avic.rong.bean.show_bean.SjbzListBean;
import com.avic.rong.course.showapi.LiveApi;
import com.avic.rong.fragment.showapi.EsInfoApi;
import com.avic.rong.fragment.showapi.FollowApi;
import com.avic.rong.fragment.showapi.SjbzListApi;
import com.avic.rong.listener.RocketOnScrollListener;
import com.avic.rong.publishVideo.activity.PublishVideoActivity;
import com.avic.rong.questionOrAnswer.DialogShare;
import com.avic.rong.questionOrAnswer.ShareUtilCallBack;
import com.avic.rong.questionOrAnswer.activity.PersonalHomeActivity;
import com.avic.rong.richEditor.RichEditorActivity;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DateUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.StringUtils;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.ScrollWebViewListion;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;
import com.example.minato.minastore.utils.AppUtils;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import wendu.dsbridge.CompletionHandler;

import static com.lzy.okgo.utils.HttpUtils.runOnUiThread;

/**
 * 首页-关注
 */
@SuppressLint("ValidFragment")
public class FragmentStandard extends BaseFragment implements OnRefreshListener, OnLoadMoreListener, ShareUtilCallBack {


    public SmartRefreshLayout refreshLayout;
    private String mTitle;
    private Context mContext;
    private List<ShowBean> followList = new ArrayList<>();
    private List<SjbzListBean> sjbzList = new ArrayList<>();
    private ArrayList<ShowBean> detailBeans;
    private List<SjbzListBean> sjbzBeans;
    private FollowApi followApi;
    private SjbzListApi sjbzListApi;
    int pageNo = 1;
    int pageSize = 20;
    boolean refresh = true;
    private FollowListAdapter bigRecommecdAdapter;
    private SjbzAdapter sjbzAdapter;
    private RecommendApi recommendApi;
    private List<EsInfoBean> beans = new ArrayList<>();
    private LoadingLayout loading_layout;
    private String loginToken;
    private View view;
    private ImageView noNetworkImg;

    private DialogShare dialogShare;
    /**
     * 立即登录
     */
    private TextView goLogin;
    private LinearLayout loginFollow;
    private LinearLayout loginDatano;
    private RecyclerView recyclerView;
    private LinearLayout otherFollow;
    private ScrollWebViewListion webView;
    private WebSettings settings;
    public NestedScrollView nestedScrollView;


    public static FragmentStandard getInstance(String title, Context context) {
        FragmentStandard sf = new FragmentStandard();
        sf.mContext = context;
        sf.mTitle = title;
        return sf;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_follow;
    }

    @Override
    protected void initView() {
        //初始化数据
        refreshLayout = fragmentView.findViewById(R.id.refreshLayout);
        loading_layout = fragmentView.findViewById(R.id.loading_layout);
        noNetworkImg = (ImageView) fragmentView.findViewById(R.id.no_network_img);
        goLogin = (TextView) fragmentView.findViewById(R.id.go_login);
        loginFollow = (LinearLayout) fragmentView.findViewById(R.id.login_follow);
        loginDatano = (LinearLayout) fragmentView.findViewById(R.id.login_datano);
        recyclerView = (RecyclerView) fragmentView.findViewById(R.id.recyclerView);
        otherFollow = (LinearLayout) fragmentView.findViewById(R.id.other_follow);
        webView = fragmentView.findViewById(R.id.webview);
        goLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), LoginPhoneActivity.class));
            }
        });
        loginToken = SharedPreferencesUtil.getLoginToken();
        bigRecommecdAdapter = new FollowListAdapter(getActivity());
        sjbzAdapter = new SjbzAdapter(getActivity());
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);

        settings = webView.getSettings();
        // 设置加载进来的页面自适应手机屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        settings.setDisplayZoomControls(false);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);

        webView.addJavascriptObject(this, null);
        //监听滚动
        nestedScrollView = fragmentView.findViewById(R.id.nest_scrollview);
        nestedScrollView.setOnScrollChangeListener(new RocketOnScrollListener(((MainActivity) getActivity())));

        webView.loadUrl(AppUtils.BASE_URL + "content/topAdv");
//        if ("世界标准日".equals(mTitle)) {
            loginDatano.setVisibility(View.GONE);
            loginFollow.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
            sjbzAdapter.setmTitle("世界标准日");
            recyclerView.setAdapter(sjbzAdapter);
            //世界标准日 请求数据
            VideoListData();
//        } else {
//            webView.setVisibility(View.GONE);
//            recyclerView.setAdapter(bigRecommecdAdapter);
//            //关注 请求数据
//            loadData();
//        }
        sjbzAdapter.setItemClickListener(new SjbzAdapter.MyClickListener() {
            @Override
            public void onItemClick(int position) {
                //分享
                if (dialogShare == null) {
                    dialogShare = new DialogShare(getActivity(), FragmentStandard.this);
                }
                if (StringUtils.isEmpty(sjbzList.get(position).getContImg())) {
                    dialogShare.showDialog("我在融融上发布了一条世界标准日动态，快给我点个赞", "快来和我一起参与世界标准日活动，发动态领礼品，集赞还可赢大奖", AppUtils.BASE_URL_H5 + "app/act/detail?contId=" + sjbzList.get(position).getContId(), "");
                } else {
                    dialogShare.showDialog("我在融融上发布了一条世界标准日动态，快给我点个赞", "快来和我一起参与世界标准日活动，发动态领礼品，集赞还可赢大奖", AppUtils.BASE_URL_H5 + "app/act/detail?contId=" + sjbzList.get(position).getContId(), sjbzList.get(position).getContImg());
                }

            }
        });

    }


//    public void loadData() {
//        followList.clear();
//        followApi = new FollowApi((MainActivity) getActivity(), httpOnNextListener);
//        loading_layout.setStatus(LoadingLayout.LOADING);
//        if (SharedPreferencesUtil.isLogin()) {
//            String login_token = SharedPreferencesUtil.getInstance(getActivity()).getLogintoken();
//            followApi.setToken(login_token);
//            followApi.setPageNo(pageNo + "");
//            followApi.setPageSize(pageSize + "");
//            followApi.setCache(false);
//
//            otherFollow.setVisibility(View.VISIBLE);
//            loginFollow.setVisibility(View.GONE);
//            loginDatano.setVisibility(View.GONE);
//            loading_layout.setStatus(loading_layout.LOADING);
//            HttpManager.getInstance().doHttpDeal(followApi);
//            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
//                @Override
//                public void onReload(View v) {
//                    HttpManager.getInstance().doHttpDeal(followApi);
//                    loading_layout.setStatus(loading_layout.LOADING);
//                }
//
//                @Override
//                public void onReturn(View v) {
//                    getActivity().onBackPressed();
//                }
//            });
//        } else {
//            loginFollow.setVisibility(View.VISIBLE);
//            loginDatano.setVisibility(View.GONE);
//            otherFollow.setVisibility(View.GONE);
//
//        }
//    }

    public void VideoListData() {
        sjbzList.clear();
        sjbzListApi = new SjbzListApi((MainActivity) getActivity(), sjbzListener);
        loading_layout.setStatus(LoadingLayout.LOADING);
        sjbzListApi.setPageNo(pageNo + "");
        sjbzListApi.setPageSize(pageSize + "");
        sjbzListApi.setCache(false);

        otherFollow.setVisibility(View.VISIBLE);
        loginFollow.setVisibility(View.GONE);
        loginDatano.setVisibility(View.GONE);
        loading_layout.setStatus(loading_layout.LOADING);
        HttpManager.getInstance().doHttpDeal(sjbzListApi);
        loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                HttpManager.getInstance().doHttpDeal(sjbzListApi);
                loading_layout.setStatus(loading_layout.LOADING);
            }

            @Override
            public void onReturn(View v) {
                getActivity().onBackPressed();
            }
        });
    }


    @Override
    public void onResume() {
//        if ("世界标准日".equals(this.mTitle)) {
            webView.setVisibility(View.VISIBLE);
            otherFollow.setVisibility(View.VISIBLE);
            loginFollow.setVisibility(View.GONE);
            loginDatano.setVisibility(View.GONE);
//        } else {
//            if (SharedPreferencesUtil.isLogin()) {
//                otherFollow.setVisibility(View.VISIBLE);
//                loginFollow.setVisibility(View.GONE);
//                loginDatano.setVisibility(View.GONE);
//                webView.setVisibility(View.GONE);
//                if (followList.size() < 1) {
//                    if (null == followApi) {
//                        return;
//                    }
//                    loginToken = SharedPreferencesUtil.getLoginToken();
//                    followApi.setPageNo(pageNo + "");
//                    followApi.setPageSize(pageSize + "");
//                    followApi.setToken(loginToken);
//                    HttpManager.getInstance().doHttpDeal(followApi);
//                }
//            } else {
//                loginFollow.setVisibility(View.VISIBLE);
//                loginDatano.setVisibility(View.GONE);
//                otherFollow.setVisibility(View.GONE);
//                webView.setVisibility(View.GONE);
//                loading_layout.setStatus(LoadingLayout.SUCCESS);
//            }
//        }


        //fragment友盟分享 监听不执行 监听只执行onStart,(onResult,onError,onCancel 不执行) 所以手动关闭
        if (dialogShare != null && dialogShare.umShareUtil != null) {
            dialogShare.umShareUtil.hideProgressDialog();
        }
        super.onResume();
    }

    //世界标准日的监听   判断是否有数据去显示隐藏
    HttpOnNextListener<BaseResultEntity> sjbzListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                loading_layout.setStatus(LoadingLayout.ERROR);
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);

            if (isRefresh) {
                refreshLayout.finishRefresh();
                refresh = true;
            } else {
                refreshLayout.finishLoadMore();
            }
            sjbzBeans = (List<SjbzListBean>) baseResultEntity.getData();
            sjbzList.addAll(sjbzBeans);
            if (sjbzList != null) {
                otherFollow.setVisibility(View.VISIBLE);
                loginDatano.setVisibility(View.GONE);
                loginFollow.setVisibility(View.GONE);
                String substring = "";
                //遍历处Id  去请求搜索补全接口
                for (int k = 0; k < sjbzList.size(); k++) {
                    String contIds = "";
                    for (int o = sjbzList.size() - 1; o >= 0; o--) {
                        int contId = sjbzList.get(o).getContId();
                        contIds += contId + ",";
                    }
                    if (contIds.length() > 0) {
                        substring = contIds.substring(0, contIds.length() - 1);
                    }
                }
                EsInfoApi esInfoApi = new EsInfoApi((MainActivity) getActivity(), EnsOnNextListener, substring);
                esInfoApi.setCache(false);
                HttpManager.getInstance().doHttpDeal(esInfoApi);
                return;

            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            Log.e("follow", "onError: " + e.getMessage());
            loading_layout.setStatus(LoadingLayout.ERROR);
        }
    };

    //关注的监听   判断是否有数据去显示隐藏
//    HttpOnNextListener<BaseResultEntity> httpOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
//        @Override
//        public void onNext(BaseResultEntity baseResultEntity) {
//            if (!baseResultEntity.getCode().equals(ConstantsUtils.STATUS_SUCCESS_200)) {
//                loading_layout.setStatus(LoadingLayout.ERROR);
//                return;
//            }
//            loading_layout.setStatus(LoadingLayout.SUCCESS);
//
//            if (baseResultEntity.getData() == null) {
//                loginFollow.setVisibility(View.GONE);
//                otherFollow.setVisibility(View.GONE);
//                loginDatano.setVisibility(View.VISIBLE);
//                return;
//            }
//            detailBeans = (ArrayList<ShowBean>) baseResultEntity.getData();
//            followList.addAll(detailBeans);
//
//            if (followList != null) {
//                otherFollow.setVisibility(View.VISIBLE);
//                loginDatano.setVisibility(View.GONE);
//                loginFollow.setVisibility(View.GONE);
//                String substring = "";
//                //遍历处Id  去请求搜索补全接口
//                for (int k = 0; k < followList.size(); k++) {
//                    if (followList.get(k) != null && followList.get(k).getType() != null) {
//                        String contIds = "";
//                        if (Integer.valueOf(followList.get(k).getType()) == 8) {
//                            List<TypeBean> data = followList.get(k).getData();
//                            for (int o = data.size() - 1; o >= 0; o--) {
//                                int contId = data.get(o).getContId();
//                                contIds += contId + ",";
//                            }
//                            if (contIds.length() > 0) {
//                                substring = contIds.substring(0, contIds.length() - 1);
//                            }
//                        }
//                    }
//                }
//                EsInfoApi esInfoApi = new EsInfoApi((MainActivity) getActivity(), EnsOnNextListener, substring);
//                esInfoApi.setCache(false);
//                HttpManager.getInstance().doHttpDeal(esInfoApi);
//                return;
//
//            }
//        }
//
//        @Override
//        public void onError(Throwable e) {
//            super.onError(e);
//            Log.e("follow", "onError: " + e.getMessage());
//            loading_layout.setStatus(LoadingLayout.ERROR);
//        }
//    };

    //搜索补全监听  最终确认数据的地方
    HttpOnNextListener<BaseResultEntity> EnsOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity baseResultEntity) {
            String code = baseResultEntity.getCode();
            if (code.equals(ConstantsUtils.STATUS_SUCCESS_200)) {
                ArrayList<EsInfoBean> esInfoBean = (ArrayList<EsInfoBean>) baseResultEntity.getData();

                if (esInfoBean != null) {
                    beans.addAll(esInfoBean);
//                    bigRecommecdAdapter.setEsData(beans);
                    sjbzAdapter.setEsData(beans);
                }

                sjbzAdapter.setData(sjbzList);
//                bigRecommecdAdapter.setBean(followList);
                loading_layout.setStatus(LoadingLayout.SUCCESS);
                if (isRefresh) {
                    refreshLayout.finishRefresh();
                    refresh = true;
                } else {
                    refreshLayout.finishLoadMore();
                }

            } else {

                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            loading_layout.setStatus(LoadingLayout.ERROR);
        }
    };



    @Override
    protected void addListener() {
    }


    //刷新
    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
//        if ("世界标准日".equals(mTitle)) {
            refresh = false;
            sjbzList.clear();
            beans.clear();
            isRefresh = true;
            pageNo = 1;
            pageSize = 10;
            sjbzListApi.setPageNo(pageNo + "");
            sjbzListApi.setPageSize(pageSize + "");
            HttpManager.getInstance().doHttpDeal(sjbzListApi);
            webView.loadUrl(AppUtils.BASE_URL + "content/topAdv");
//        } else {
//            refresh = false;
//            followList.clear();
//            beans.clear();
//            isRefresh = true;
//            pageNo = 1;
//            pageSize = 10;
//            followApi.setPageNo(pageNo + "");
//            followApi.setPageSize(pageSize + "");
//            followApi.setToken(loginToken);
//            HttpManager.getInstance().doHttpDeal(followApi);
//        }
    }

    //加载更多
    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
//        if ("世界标准日".equals(mTitle)) {
            isRefresh = false;
            pageNo += 1;
            sjbzListApi.setPageNo(pageNo + "");
            sjbzListApi.setPageSize(pageSize + "");
            HttpManager.getInstance().doHttpDeal(sjbzListApi);
//        } else {
//            isRefresh = false;
//            pageNo += 1;
//            followApi.setPageNo(pageNo + "");
//            followApi.setPageSize(pageSize + "");
//            followApi.setToken(loginToken);
//            HttpManager.getInstance().doHttpDeal(followApi);
//        }

    }


    @JavascriptInterface
    public void toRanking(Object msg, CompletionHandler<String> handler) {
        startActivity(RankingListActivity.queryIntent(context, AppUtils.BASE_URL + "content/standardDay19/ranking?token=" + Uri.encode(SharedPreferencesUtil.getLoginToken())));
        handler.complete("success");
    }

    @JavascriptInterface
    public void shareContent(Object msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                Log.e("====shareContent", "调用了" + msg);
                //分享
                if (dialogShare == null) {
                    dialogShare = new DialogShare(getActivity(), FragmentStandard.this);
                }

                dialogShare.showDialog("快来和我一起参加世界标准日活动，赢60万大奖", "在融融发布我的世界标准日动态，转发即可领礼品，集赞还可赢大奖", AppUtils.BASE_URL_H5 + "app/act/list", "");

            }
        });
    }

    @JavascriptInterface
    public void publicImage(Object msg) {
        startActivity(RichEditorActivity.getIntent(getContext(), RichEditorActivity.class));
    }

    @JavascriptInterface
    public void publicVideo(Object msg) {
        startActivity(RichEditorActivity.getIntent(getContext(), PublishVideoActivity.class));

    }

    @JavascriptInterface
    public void openUserCenter(Object msg, CompletionHandler<String> handler) {

        if (DateUtils.isFastDoubleClick()) return;

        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(msg.toString());
            String userId = jsonObject.getString("userId");
            Intent intent = new Intent(getActivity(), PersonalHomeActivity.class);
            intent.putExtra("homeUserID", userId);
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @JavascriptInterface
    public void watchVideo(Object msg, CompletionHandler<String> handler) {
//        直播

        if (SharedPreferencesUtil.isLogin()) {
            LiveApi liveApi = new LiveApi((MainActivity) getActivity(), liveListener);
            liveApi.setArgument(SharedPreferencesUtil.getLoginToken(), msg + "");
            liveApi.setCache(false);
            HttpManager.getInstance().doHttpDeal(liveApi);
        } else {
//            ToastTools.showToast("请先登录");
            startActivity(new Intent(mContext, LoginPhoneActivity.class));
        }
    }

    @Override
    public void shareSuccess() {

    }

    @Override
    public void shareFailed() {

    }

    @Override
    public void shareCancel() {

    }

    HttpOnNextListener<BaseResultEntity> liveListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity channelBean) {
            if (!channelBean.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(getActivity(), channelBean.getMsg());
                return;
            }
            String data = (String) channelBean.getData();
            Logger.i("--------------------" + data);
            startActivity(TestWebActivity.queryIntent(getActivity(), data));


        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
        }
    };


}